package com.yanfan.zutai.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.yanfan.common.config.RuoYiConfig;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.model.LoginUser;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.common.utils.file.FileUploadUtils;
import com.yanfan.zutai.mapper.BCommonMapper;
import com.yanfan.zutai.domain.SysUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/zutai")
public class ZutaiUploadController extends BaseController {

    @Autowired
    private BCommonMapper commonMapper;


    @PostMapping("/upload/uploadData")
    public AjaxResult importData(MultipartFile file, String moduleName, String moduleGuid, Boolean isMultiple) throws Exception {
        if (isMultiple == null) {
            // 判断图片是否多条上传
            isMultiple = false;
        }
        if (!file.isEmpty()) {
            String avatar = "";
            try {
                avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            } catch (Exception e) {
                return AjaxResult.error(500, "上传组件异常，" + e);
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUpload sysUpload = new SysUpload();
            if (loginUser.getUser().getDeptId() != null) {
                String deptIds = "," + loginUser.getUser().getDept().getAncestors() + "," + loginUser
                        .getUser()
                        .getDeptId() + ",";
                sysUpload.setDeptIdStrs(deptIds);
            }
            String fileName = file.getOriginalFilename();
            if ("云组态".equals(moduleGuid) && fileName.length() > 10) {
                fileName = moduleName;
            }
            sysUpload.setFileName(fileName);
            sysUpload.setModuleName(moduleName);
            sysUpload.setUpdateBy(loginUser.getUsername());
            sysUpload.setUpdateTime(new Date());
            sysUpload.setResourceUrl(avatar);
            sysUpload.setModuleGuid(moduleGuid);
            if (StrUtil.isNotBlank(sysUpload.getModuleGuid()) && !isMultiple) {
                SysUpload sysUploadQuery = new SysUpload();
                sysUploadQuery.setModuleGuid(moduleGuid);
                sysUploadQuery.setModuleName(moduleName);
                List<SysUpload> sysUploads = commonMapper.selectSysUploadList(sysUploadQuery);
                if (sysUploads.size() > 0) {
                    sysUpload.setId(sysUploads.get(0).getId());
                    sysUpload.setUpdateTime(new Date());
                    commonMapper.updateSysUpload(sysUpload);
                    if (StrUtil.isNotBlank(sysUploads.get(0).getResourceUrl())) {
                        String newUrl = sysUploads
                                .get(0)
                                .getResourceUrl()
                                .replace("/profile", "")
                                .replace("/avatar", "");
                        File fileQuery = new File(RuoYiConfig.getAvatarPath() + newUrl);
                        if (fileQuery.exists()) {
                            System.out.println("删除之前的图片资源");
                            fileQuery.delete();
                        }
                    }
                } else {
                    // 生成19位的唯一id
                    Snowflake snowflake = IdUtil.getSnowflake(6, 2);
                    long id = snowflake.nextId();
                    sysUpload.setId(id);
                    commonMapper.insertSysUpload(sysUpload);
                }
            } else {
                // 生成19位的唯一id
                Snowflake snowflake = IdUtil.getSnowflake(6, 2);
                long id = snowflake.nextId();
                sysUpload.setId(id);
                commonMapper.insertSysUpload(sysUpload);
            }
            return AjaxResult.success("上传组件成功");
        }
        return AjaxResult.error(500, "上传组件异常，请联系管理员");
    }

    @DeleteMapping("/upload/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            Long id = ids[i];
            SysUpload sysUpload = commonMapper.selectSysUploadById(id);
            if (StrUtil.isNotBlank(sysUpload.getResourceUrl())) {
                String newUrl = sysUpload.getResourceUrl().replace("/profile", "").replace("/avatar", "");
                File file = new File(RuoYiConfig.getAvatarPath() + newUrl);
                if (file.exists()) {
                    System.out.println("删除成功");
                    file.delete();
                }
            }
        }
        commonMapper.deleteSysUploadByIds(ids);
        return toAjax(true);
    }

    @PutMapping("/upload")
    public AjaxResult edit(@RequestBody SysUpload sysUpload) {
        sysUpload.setUpdateTime(new Date());
        return toAjax(commonMapper.updateSysUpload(sysUpload));
    }
}
